
import json

from datetime import datetime
from typing import List


CONFIG_PATH = 'config.cfg'


class TimerConfig:
    def __init__(self, datetime: datetime, annual: bool, event: str):
        self.datetime = datetime
        self.annual = annual
        self.event = event
        self.x = 687
        self.y = 12

        self.set_xy_handler = lambda : None


def load_config_list(json_str: str, handler=lambda: None) -> List[TimerConfig]:
    cfgs = []

    c_json: dict = json.loads(json_str)
    timers = c_json.get('timers', [])
    if not timers:
        return []

    for t in timers:
        annual = bool(t['annual'])
        name = str(t['name'])
        stamp = int(t['stamp'])
        x = int(t['x'])
        y = int(t['y'])
        config = TimerConfig(
            datetime.fromtimestamp(stamp), annual, name
        )
        config.set_xy_handler = handler
        config.x = x
        config.y = y
        cfgs.append(config)
    
    print('load: %s' % json_str)

    return cfgs


def make_config_json(cfgs: List[TimerConfig]):
    j_dict = {}
    timers = []

    for config in cfgs:
        c_dict = {
            'annual': config.annual,
            'name': config.event,
            'stamp': int(config.datetime.timestamp()),
            'x': int(config.x),
            'y': int(config.y),
        }
        timers.append(c_dict)

    j_dict['timers'] = timers

    o = json.dumps(j_dict)
    print('save output: %s' % o)
    return o
